﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // //窗口界面初始化
    // weightInit();


    //创建一个485串口连接对象
    serialPort_485 = new rs485_connect;

    //初始化刷新串口列表函数
    this->refreshPortList();

    //初始化信号与槽的连接函数
    this->signalConnectToSlots();
}

MainWindow::~MainWindow()
{
    delete ui;
}


// void MainWindow::weightInit()
// {
//     //在这里进行窗口界面的初始化
//     reFreshPorts = new QPushButton;
//     connect2Port = new QPushButton;
//     comboxPorts = new QComboBox;
//     textBr_diaplament = new QTextBrowser;
//     edit_send2Ehternet = new QLineEdit;

//     QGridLayout *itemLay = new QGridLayout;



//     //直接将主界面作为布局的基本界面进行布局
//     this->setLayout(itemLay);


// }

void MainWindow::refreshPortList()
{
    ui->comboBox_name->clear();
    QStringList portList;
    foreach (const QSerialPortInfo& info, QSerialPortInfo::availablePorts())
    {
        portList.append(info.portName());
    }
    ui->comboBox_name->addItems(portList);
}

//信号触发函数，将信号发送出去
void MainWindow::Connect2Port()
{
    emit signal_msg2port(ui->comboBox_name->currentText());
}

//在这里实现各种槽函数的连接
void MainWindow::signalConnectToSlots()
{
    connect(ui->pushButton_refresh, &QPushButton::clicked, this, &MainWindow::refreshPortList);

    connect(ui->pushButton_connect, &QPushButton::clicked, this, &MainWindow::Connect2Port);

    //初始化端口的函数，将端口的信息进行传递
    connect(this, &MainWindow::signal_msg2port, serialPort_485, &rs485_connect::initPort);

    //主要响应其中两个连接状态信号函数
    connect(serialPort_485, &rs485_connect::succeed, this, [ = ]
    {
        qDebug() << "连接成功";

    });
    connect(serialPort_485, &rs485_connect::faild, this, [ = ]
    {
        qDebug() << "连接错误";
    });


    //处理发送过来的数据，现在主要是在界面上进行显示
    connect(serialPort_485, &rs485_connect::result, this, [ = ](int addr, double data)
    {
        switch(addr)
        {
            case 0:
                ui->lineEdit_displament->setText(QString::number(data));
                break;
            case 1:
                ui->lineEdit_msg2port->setText(QString::number(data));
                break;
        }

    });
}


